package com.auto.uhoo.tools;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.auto.uhoo.ui.base.BaseActivity;

/**
 * Created by HHD on 2016/12/6.
 */

public class Jumper {

    private final String TAG = Jumper.class.getSimpleName();

    private static Jumper instance = new Jumper();

    public final static String ACTION_STANDARD = "com.auto.uhoo.standard";//标准启动

    public final static String KEY_TARGET_FRAGMENT = "target";
    public final static String KEY_BACK_STACK = "back_stack";

    public Context context;
    public Bundle bundle;
    public String action;
    public String targetFragment;
    public boolean newActivity;
    public boolean forResult;
    public int requestCode = 0;

    public static Jumper getInstance(){
        return instance;
    }

    public void jumpTo(Context context, String targetFragment){
        jumpTo(context, null, false, 0, targetFragment, null);
    }

    public void jumpTo(Context context, String action, String targetFragment, Bundle bundle){
        jumpTo(context, action, false, 0, targetFragment, bundle);
    }

    public void jumpTo(Context context, String action, String targetFragment){
        jumpTo(context, action, false, 0, targetFragment, null);
    }

    public void jumpTo(Context context, String action, boolean forResult, int requestCode,
                       String targetFragment, Bundle bundle){

        this.context = context;
        this.action = action;
        this.forResult = forResult;
        this.requestCode = requestCode;
        this.targetFragment = targetFragment;
        this.bundle = bundle;

        Intent intent = buildIntent();
        if (!TextUtils.isEmpty(action)){
            if (!(context instanceof Activity)){
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            if (forResult){
                ((Activity)context).startActivityForResult(intent, requestCode);
            }else{
                context.startActivity(intent);
            }
        }else{
            if (context instanceof BaseActivity){
                ((BaseActivity)context).showFragment(intent);
            }else{
                LOG.e(TAG, "error");
            }
        }

    }

    private Intent buildIntent(){
        Intent intent = new Intent();

        intent.putExtra(KEY_TARGET_FRAGMENT, targetFragment);
        intent.putExtra(KEY_BACK_STACK, true);//默认全部添加回退栈
        if (!TextUtils.isEmpty(action)){
            intent.setAction(action);
            newActivity = true;
        }else{
            newActivity = false;
        }

        return intent;
    }

}
